package com.pj.wisdomlogistics.ui.view.recyclerview;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

/**
 * Created by wufan on 2017/5/4.
 */

public abstract class EndlessRecyclerOnScrollListener extends
        RecyclerView.OnScrollListener {

    private int previousTotal = 0;
    private boolean loading = false;
    int firstVisibleItem, visibleItemCount, totalItemCount;

    private int currentPage = 1;
    private boolean isUp;

    private LinearLayoutManager mLinearLayoutManager;

    public EndlessRecyclerOnScrollListener(
            LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();


        if (mTouchListener == null) {
            mTouchListener = new View.OnTouchListener() {
                private float preY = 0;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_MOVE){
                        float y = event.getY();
                        if(y > preY){
                            isUp = false;
                        }else if(y < preY){
                            isUp = true;
                        }
                        preY = y;
                    }
                    return false;
                }
            };
            recyclerView.setOnTouchListener(mTouchListener);
        }




        if (!loading && newState == SCROLL_STATE_IDLE  && isUp
                && (totalItemCount - visibleItemCount) <= firstVisibleItem) {
            currentPage++;
            loading = true;
            onLoadMore(currentPage);
        }
    }

    public abstract void onLoadMore(int currentPage);

    public void setLoading(boolean loading){
        this.loading = loading;
        if(!isUp){
            currentPage = 1;
        }
    }

    View.OnTouchListener mTouchListener = null;
}


